#!/usr/bin/env python
import os
from pathlib import Path
from base64 import urlsafe_b64encode
from os.path import join,getsize
from moviepy.video.io.VideoFileClip import VideoFileClip
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
from time import time
import shutil
import hashlib
 
def file_md5(file_path):
    md5_obj = hashlib.md5()
    with open(file_path,'rb') as f:
        while True:
            d = f.read(8096)
            if not d:
                break
            md5_obj.update(d)
    hash_code = md5_obj.digest()
    return urlsafe_b64encode(hash_code).rstrip(b"=").decode('utf-8')

ROOT_PATH = f"{Path.home()}/Downloads"
OUT_PATH = join(ROOT_PATH,"video")


def cutv(filepath):
    suffix = filepath.rsplit(".",1).pop().lower() 
    if suffix not in ("mp4","mkv","avi"):
        return
    if getsize(filepath) > (100*1024*1024):
        duration = VideoFileClip(filepath).duration
        print(filepath, duration)
        filename = file_md5(filepath)
        print(filename)
        ffmpeg_extract_subclip(filepath, 50.51, duration, targetname=f"{OUT_PATH}/{filename}.{suffix}")
        os.remove(filepath)
        

def main():
    os.makedirs(OUT_PATH,exist_ok=True)

    for root, dirs, files in os.walk(ROOT_PATH):
        if root == OUT_PATH:
            continue
        for i in files:
            cutv(join(root,i))

if __name__ == "__main__":
    main()
